﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Web.PuntoDeVenta.Code;
using Web.Framework;
using CrmContacto.Contracts.Contracts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Configuration;
using Web.Framework.Translate;
using Web.Framework.Misc;
using System.Reflection;
using System.IO;

namespace Web.PuntoDeVenta
{
    public partial class SiteMaster : BaseMasterPage
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
        }

        private void cboPickerSubPtoVta_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList cboPickerSubPtoVta = (DropDownList)sender;
            // Cambiar el punto de venta
            var ptoVta = BasePage.GetPuntoDeVentaCurrent();
            if (ptoVta != null)
            {
                ptoVta.SubPuntoDeVentaIdActual = Convert.ToInt32(cboPickerSubPtoVta.SelectedValue);
            }
        }

        public override void PreLoad(List<string> operations)
        {
            if (!this.DesignMode)
            {
                try
                {
                    base.PreLoad(operations);
                    this.pnlMessages.CssClass = "pnlMessagesClass displayNone";
                    ExceptionManager.Instance.WebMessager = this;
                    this.txtMessages.Text = string.Empty;
                    BuildMenu();

                    LoginStatus status = (LoginStatus)HeadLoginView.FindControl("HeadLoginStatus");
                    if (status != null)
                    {
                        status.LoggedOut += new EventHandler(LoginStatusEvent_LoggedOut);
                    }

                    DropDownList cboPickerSubPtoVta = (DropDownList)HeadLoginView.FindControl("cboPickerSubPtoVta");
                    if (cboPickerSubPtoVta != null)
                    {
                        cboPickerSubPtoVta.AutoPostBack = true;
                        cboPickerSubPtoVta.SelectedIndexChanged += new EventHandler(cboPickerSubPtoVta_SelectedIndexChanged);
                    }
                }
                catch (Exception ex)
                {
                    ExceptionManager.Instance.HandleException(ex);
                }
            }
        }

        private void LoadSubPtoVta()
        {
            DropDownList cboPickerSubPtoVta = (DropDownList)HeadLoginView.FindControl("cboPickerSubPtoVta");
            if (cboPickerSubPtoVta != null)
            {
                var ptoVta = BasePage.GetPuntoDeVentaCurrent();
                if (ptoVta != null)
                {
                    UIHelper.LoadCbo(ptoVta.SubPuntosDeVenta, cboPickerSubPtoVta, string.Empty, "Id", "Codigo");
                    if (ptoVta.SubPuntoDeVentaIdActual.HasValue)
                    {
                        cboPickerSubPtoVta.SelectedValue = ptoVta.SubPuntoDeVentaIdActual.Value.ToString();
                    }
                }
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (this.Page.User.Identity.IsAuthenticated)
                {
                    Label loginName = (Label)this.HeadLoginView.FindControl("lblLoginName");
                    loginName.Text = BaseWebPage.DisplayUserName;
                }                

                this.pnlMessages.CssClass = "pnlMessagesClass displayNone";

                Control ctrlBienvenido = this.HeadLoginView.FindControl("lblPtoVtaBienvenido");
                if (ctrlBienvenido != null)
                {
                    Label lblBienvendioPtoVta = (Label)ctrlBienvenido;
                    List<string> cookieCompany = HttpHelper.GetCookieValues(HttpHelper.cookieCompany, this.Request);
                    List<string> cookiePtoVta = HttpHelper.GetCookieValues(HttpHelper.cookiePtoVtaName, this.Request);

                    if (cookieCompany.Count > 1 && cookiePtoVta.Count > 1)
                    {
                        var ptoVta = BasePage.GetPuntoDeVentaCurrent();
                        lblBienvendioPtoVta.Text = ptoVta.DisplayName;
                    }
                }

                if (!this.IsPostBack)
                {
                    SetVersion();
                    LoadSubPtoVta();
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            CustomizeCompanyLookAndFeel();
        }

        private void LoginStatusEvent_LoggedOut(Object sender, System.EventArgs e)
        {
            try
            {
                Session.Clear();
                Session.Abandon();
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void SetVersion()
        {
            string oVersionNumero = Convert.ToString(StoreHelper.GetObject("versionNumero"));
            string oVersionText = Convert.ToString(StoreHelper.GetObject("versionTexto"));

            if (String.IsNullOrEmpty(oVersionNumero))
            {
                oVersionNumero = Assembly.GetExecutingAssembly().GetName().Version.ToString();
                StoreHelper.StoreObject("versionNumero", oVersionNumero);
            }

            if (String.IsNullOrEmpty(oVersionText))
            {
                string path = ConfigurationManager.AppSettings["VersionTextPath"];
                oVersionText = File.ReadAllText(path);
                StoreHelper.StoreObject("versionTexto", oVersionText);
            }

            this.lblAppVersion.Text = LocalizationProvider.Instance["Bo.Version.Numero"] + oVersionNumero;
            this.lblAppText.Text = LocalizationProvider.Instance["Bo.Version.Fecha"] + oVersionText;
        }

        private void LocalizeControls()
        {
            //lblTituloCrm.Text = LocalizationProvider.Instance["lblTituloCrm"];
        }

        private void CustomizeCompanyLookAndFeel()
        {
            int? companyId = null;
            bool loadFromCookie = false;
            try
            {
                companyId = BaseMasterPage.CompanyId;
                if (companyId == 0)
                {
                    loadFromCookie = true;
                }
            }
            catch
            {
                loadFromCookie = true;
            }

            if (loadFromCookie)
            {
                List<string> cookieCompany = HttpHelper.GetCookieValues(HttpHelper.cookieCompany, this.Request);
                if (cookieCompany.Count > 1)
                {
                    companyId = Convert.ToInt32(cookieCompany[0]);
                }
            }

            if (companyId.HasValue)
            {
                CompanyConfiguration companyConfiguration = BasePage.GetCompanyConfigurationList(this.Page).Where(c => c.CompanyId == companyId.Value).SingleOrDefault();
                if (companyConfiguration != null)
                {
                    if (!String.IsNullOrEmpty(companyConfiguration.CssFilePath))
                    {
                        HtmlLink myHtmlLink = new HtmlLink();
                        myHtmlLink.Href = string.Format("/Styles/Company/{0}", companyConfiguration.CssFilePath);
                        myHtmlLink.Attributes.Add("rel", "stylesheet");
                        myHtmlLink.Attributes.Add("type", "text/css");
                        Page.Header.Controls.Add(myHtmlLink);
                    }

                    if (!String.IsNullOrEmpty(companyConfiguration.LogoImgFilePath))
                    {
                        this.ImgEmpresa.ImageUrl = companyConfiguration.LogoImgFilePath;
                    }
                }
            }
            else
            {
                this.ImgEmpresa.CssClass = "displayNone";
            }
        }

        public override void ShowMessage(string message, WebMessageType type)
        {
            ShowMessage(LocalizationProvider.Instance["Bo.Messages.Mensaje"], message, type);
        }

        public override void ShowMessage(string title, string message, WebMessageType type)
        {
            this.pnlMessages.CssClass = "pnlMessagesClass displayBlock";
            this.txtErrorTitle.Text = title;
            this.txtMessages.Text = message;
            if (type != WebMessageType.Error)
            {
                pnlError.CssClass = "errorPanelMessage";
            }
            else
            {
                pnlError.CssClass = "errorPanelError";
            }
        }

        public override void MakeMenuVisible(bool visible)
        {
            //this.NavigationMenu.Visible = visible;
        }

        public override void BuildMenu()
        {

        }
    }
}
